package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.Shopping_cart;
import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.getShopCart.GetShopCartResp;
import com.icefish.dao.Shopping_cartDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.Init_Req_Resp_Config;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/getShopCartById")
public class getShopCartById extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 标准初始化配置
        Init_Req_Resp_Config.init(request,response);
        // 捞取 用户id
        Integer user_id = Integer.parseInt(request.getParameter("user_id"));
        // 查询用户相关购物车数据
        Shopping_cartDao scd = DaoFactory.getShopping_cartDaoInstance();

        ArrayList<Shopping_cart> shopping_carts = null;
        boolean flag =false;
        try {
             shopping_carts = scd.selectAllShopCartByUserId(user_id);
             flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 封装结果集成json数据，响应给浏览器
        GetShopCartResp shopCartResp= new GetShopCartResp();
        if (flag) {
            shopCartResp.setData(shopping_carts);
            shopCartResp.setMeta(new Meta("获取用户相关购物车成功",200));
        }
        else {
            shopCartResp.setMeta(new Meta("获取用户相关购物车失败",500));
        }

        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(shopCartResp);

        // 响应数据
        response.getWriter().write(backToBrowser);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
